/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
 */
package td.client.presenter;

import java.util.ArrayList;

import td.client.ClientState;
import td.client.place.NameTokens;
import td.client.presenter.handlers.DetailUiHandlers;
import td.client.presenter.handlers.ThoughtListingUiHandlers;
import td.client.presenter.handlers.ThoughtListingUiHandlers.MyView;
import td.domain.Category;
import td.domain.DemoStore;
import td.domain.StatisticalGrouping;
import td.domain.StatisticalGrouping.GroupType;
import td.domain.TagDef;
import td.domain.Thought;
import td.domain.Topic;
import td.domain.util.StatisticalComparison;
import td.pt.event.HideAllPopupsEvent;
import td.pt.event.ThoughtListingEvent;
import td.pt.event.ThoughtListingEvent.ThoughtListingHandler;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.inject.Inject;
import com.google.web.bindery.event.shared.EventBus;
import com.gwtplatform.mvp.client.Presenter;
import com.gwtplatform.mvp.client.annotations.NameToken;
import com.gwtplatform.mvp.client.annotations.ProxyCodeSplit;
import com.gwtplatform.mvp.client.proxy.PlaceRequest;
import com.gwtplatform.mvp.client.proxy.ProxyPlace;
import com.gwtplatform.mvp.client.proxy.RevealContentEvent;

/**
 * Presents a listing of any Statistical grouping.
 * 
 * @author Artem Shamsutdinov
 * 
 */
public class ThoughtListingPresenter extends
		Presenter<MyView, ThoughtListingPresenter.MyProxy> implements
		ThoughtListingUiHandlers, ThoughtListingHandler<StatisticalGrouping> {

	public enum TopListType {
		NUM_READ, NUM_TAGGINGS, NUM_REFERENCED
	}

	@ProxyCodeSplit
	@NameToken(NameTokens.listing)
	public interface MyProxy extends ProxyPlace<ThoughtListingPresenter> {
	}

	@Inject
	ClientState state;

	private StatisticalGrouping currentGrouping;

	String name;
	private String type;
	Long statisticalGroupingId;

	@Inject
	public ThoughtListingPresenter(final EventBus eventBus, final MyView view,
			final MyProxy proxy) {
		super(eventBus, view, proxy);
	}

	@Override
	protected void revealInParent() {
		RevealContentEvent.fire(this, RootPresenter.SLOT_content, this);
	}

	@Override
	public void prepareFromRequest(final PlaceRequest request) {
		super.prepareFromRequest(request);
		name = request.getParameter(DetailUiHandlers.NAME,
				DetailUiHandlers.DEFAULT_NAME);
		type = request.getParameter(DetailUiHandlers.TYPE,
				StatisticalGrouping.GroupType.CATEGORY.name());
		try {
			statisticalGroupingId = Long.parseLong(name);
		} catch (NumberFormatException nfe) {
			// TODO: always default to the root category?
			statisticalGroupingId = DemoStore.db().rootCategory.getId();
			type = StatisticalGrouping.GroupType.CATEGORY.name();
		}
		StatisticalGrouping statisticalGrouping = null;
		GroupType typeFromUrl = StatisticalGrouping.getTypeFromUrl(type);
		switch (typeFromUrl) {
		case CATEGORY:
			for (Category category : DemoStore.db().allCategoryList) {
				if (category.getId().equals(statisticalGroupingId)) {
					statisticalGrouping = category;
					break;
				}
			}
			break;
		case TAG:
			for (TagDef tagDef : DemoStore.db().allTagList) {
				if (tagDef.getId().equals(statisticalGroupingId)) {
					statisticalGrouping = tagDef;
					break;
				}
			}
			break;
		case TOPIC:
			for (Topic topic : DemoStore.db().allTopicList) {
				if (topic.getId().equals(statisticalGroupingId)) {
					statisticalGrouping = topic;
					break;
				}
			}
			break;
		}
		state.setCurrentThought(null);
		state.setCurrentPlace(NameTokens.getListing());
		HideAllPopupsEvent hideAllPopupsEvent = new HideAllPopupsEvent();
		getEventBus().fireEvent(hideAllPopupsEvent);
		if (statisticalGrouping == null) {
			statisticalGrouping = DemoStore.db().rootCategory;
		}
		getView().getListingTitle().setText(
				"Top Thoughts for the " + statisticalGrouping.getName() + " "
						+ type.toLowerCase());

		refresh(statisticalGrouping);
	}

	@Override
	protected void onBind() {
		super.onBind();
		registerHandler(getEventBus()
				.addHandler(ThoughtListingEvent.TYPE, this));
		getView().getTopRead().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				getView().addNumReadsColumn();
				ArrayList<Thought> thoughts = currentGrouping.getThoughts();
				Thought.currentComparisonType = StatisticalComparison.NUMBER_OF_THOUGHT_READS;
				java.util.Collections.sort(thoughts);
				refresh(currentGrouping, thoughts);
			}
		});
		getView().getTopTaggings().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				getView().addNumTaggingsColumn();
				ArrayList<Thought> thoughts = currentGrouping.getThoughts();
				Thought.currentComparisonType = StatisticalComparison.NUMBER_OF_TAGGINGS;
				java.util.Collections.sort(thoughts);
				refresh(currentGrouping, thoughts);
			}
		});
		getView().getTopReferenced().addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				getView().addNumReferencedColumn();
				ArrayList<Thought> thoughts = currentGrouping.getThoughts();
				Thought.currentComparisonType = StatisticalComparison.NUMBER_OF_REFERENCED;
				java.util.Collections.sort(thoughts);
				refresh(currentGrouping, thoughts);
			}
		});
	}

	@Override
	protected void onReset() {
		// TODO Auto-generated method stub
		super.onReset();
		if (getView().getCellTable().getRowCount() < 1) {
			refresh(DemoStore.db().rootCategory);
		}
	}

	private void refresh(StatisticalGrouping statsGrouping) {
		refresh(statsGrouping, statsGrouping.getThoughts());
	}

	private void refresh(StatisticalGrouping statsGrouping,
			ArrayList<Thought> thoughts) {
		this.currentGrouping = statsGrouping;
		getView().getCellTable().setRowData(thoughts);
		getView().getCellTable().setPageSize(12);
		getView().getDataProvider().getList().clear();
		getView().getDataProvider().getList().addAll(thoughts);
		getView().refresh();
	}

	@Override
	public void onNewGroupingListing(
			ThoughtListingEvent<StatisticalGrouping> event) {
		state.setCurrentThought(null);
		StatisticalGrouping statsGrouping = event.getStatistics();
		if (event.geTitleString() != null) {
			getView().getListingTitle().setText(event.geTitleString());
		}
		refresh(statsGrouping);
		state.setCurrentPlace(NameTokens.getListing());
	}
}
